//
//  ICMessageVController+Logic.m
//  ICome
//
//  Created by Administrator on 2016/10/25.
//  Copyright © 2016年 iCom. All rights reserved.
//

#import "ICMessageVController+Logic.h"

#import "ICSyncManager.h"
#import "ICMessageTableViewCell.h"
#import "ICShareViewController.h"
#import "ICNavigationController.h"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wprotocol"
@implementation ICMessageVController (Logic)
#pragma clang diagnostic pop

#pragma mark - network

#pragma mark - UI
- (void)setNav {
    self.navigationItem.titleView = self.loading;
    [self.loading startLoading];
    [self sync];
    WEAKSELF
    // 根据不同状态表现不同提示
    [[ICSyncManager sharedInstance] setSyncLoadingStatusChangeBlock:^(ICSyncLoadingStatus status) {
        if (status == ICSyncLoadingStatusNotNetWork) {
            NSLog(@"网络断开 或者连接不上");
            [weakSelf.loading endLoading];
            weakSelf.loading.titleLabel.text = [NSString stringWithFormat:@"%@(未连接)",@"会话"];//@"消息(未连接)";
        } else if (status == ICSyncLoadingStatusConnecting) {
            NSLog(@"开始建立连接");
            [weakSelf.loading startLoading];
            weakSelf.loading.titleLabel.text = @"连接中...";
        } else if (status == ICSyncLoadingStatusConnectComplete) {
            NSLog(@"连接成功");
            weakSelf.loading.titleLabel.text = @"收取中...";
        } else if (status == ICSyncLoadingStatusFinish) {
            NSLog(@"同步结束");
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.loading endLoading];
                weakSelf.loading.titleLabel.text = @"会话";
                [weakSelf.tableView.mj_header endRefreshing];
                [weakSelf setSystemShareInfo];
                // 同步成功后的一些操作<分享、系统分享信息存储>
                [[ICSyncManager sharedInstance] dispatch_after_shareInfo];
            });
        } else if (status == ICSyncLoadingStatusFailure) {
            NSLog(@"同步失败");
            [weakSelf.loading endLoading];
            weakSelf.loading.titleLabel.text = @"会话";
        }
    } Synchronous:^(CGFloat pro) {
    
    }];
}


- (BOOL)push:(NSDictionary *)param {
    [super push:param];
    if ([param[@"class"] isEqualToString:@"im"]) {
        if ([param[@"subClass"] isEqualToString:@"share"]) {
            ICShareViewController *shareVc = [[ICShareViewController alloc] init];
            shareVc.shareContent = param;
            shareVc.delegate = self;
            ICNavigationController *nvc = [[ICNavigationController alloc] initWithRootViewController:shareVc];
            [self presentViewController:nvc animated:NO completion:nil];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:NotificationPushDidReceived object:nil];
            });
        }
        return YES;
    }
    return NO;
}



// 标记已读
- (void)markerReadWithIndexPath:(NSIndexPath *)indexPath currentUnReadCount:(int)unReadCount
{
    ICMessageTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:cell.group.gId count:unReadCount > 0 ? 0 : 1];
    ICGroup * group              = self.dataArray[indexPath.row];
    group.unReadCount            = unReadCount > 0 ? 0 : 1;
    [self.tableView reloadRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationNone];
}

- (void)setTopCellWithIndexPath:(NSIndexPath *)indexPath currentTop:(BOOL)isTop
{
    ICMessageTableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
    [ICMessageDatabase makeGroupTop:cell.group isTop:!isTop lastMsgTime:[ICMessageHelper currentMessageTime]];
    // 数据源改变
    [self reloadDataSource];
}

- (void)deleteLocalGroup:(NSIndexPath *)indexPath
{
    ICGroup *group = self.dataArray[indexPath.row];
    [ICMessageDatabase updateGroupUnreadMessageCountWithGroupId:group.gId count:0];
    [ICMessageDatabase changeGroupLocalType:0 GroupId:group.gId];
    [self.dataArray removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowAtIndexPath:indexPath withRowAnimation:UITableViewRowAnimationFade];
    
    if (self.dataArray.count > 0) {
        self.emptyView.hidden = YES;
    } else {
        self.emptyView.hidden = NO;
    }
}

- (void)setSystemShareInfo {
    // 数据共享
    if (self.dataArray.count > 1) {
        NSMutableArray *shareGroups = [[NSMutableArray alloc] init];
        for (ICGroup *group in self.dataArray) {
            if (group.valid == 1) {
                [shareGroups addObject:@{@"gName":group.gName == nil ? @"":group.gName,
                                         @"gId":group.gId,
                                         @"photoURL":[ICTools getMinImageURL:(group.photoId)]}];
            }
        }
        NSUserDefaults *userdef = [[NSUserDefaults alloc] initWithSuiteName:@"group.cn.icom.app"];
        
        //联系人写入共享文件
        NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.cn.icom.app"];
        NSURL *fileURL = [containerURL URLByAppendingPathComponent:@"contacts.json"];
        [shareGroups writeToURL:fileURL atomically:YES];
        
        [userdef setObject:[ICTools getToken] forKey:@"shareToken"];
        
        [userdef setObject:[ICUser currentUser].eId forKey:@"userId"];
        [userdef setObject:[ICUser currentUser].eName forKey:@"userName"];
        [userdef synchronize];
    }
}

// 置顶的送达号
- (void)updateTopDelivers:(NSArray *)dto
{
    [ICMessageDatabase cancelDeliversTopStatus];
    for (int i = 0; i < dto.count; i ++) {
        NSString *dId = dto[i];
        [ICMessageDatabase updateDeliverTopStatus:dId
                                         topOrder:i];
    }
}

- (void)searchResultWithText:(NSString *)text
{
    __weak typeof(self)weak_self = self;
    [ICMessageDatabase searchGroupWithSearchText:text finish:^(NSArray *array, NSError *error) {
        ICGroupSearchController *groupSearchVC = (ICGroupSearchController *)weak_self.searchController.searchResultsController;
        groupSearchVC.keyString = text;
        groupSearchVC.dataArray = array;
    }];
}

- (void)isRedCircleAppear {
    BOOL isAppear = NO;
    for(NSInteger i = 0; i < self.dataArray.count; i++)
    {
        ICGroup * group = self.dataArray[i];
        if(group.unReadCount > 0)
        {
            isAppear =  YES;
        }
    }
    
    if (isAppear) {
        [self.tabBarController.tabBar showBadgeOnItemIndex:self.tabBarIndex];
    } else {
        [self.tabBarController.tabBar hideBadgeOnItemIndex:self.tabBarIndex];
    }
}

@end
